package main.observer.pattern.Demo2;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by DELL
 * Date: 2019/9/27.
 * Time: 8:22
 */
interface IObserver{
    void update(int i);
}
class Observer1 implements IObserver{

    @Override
    public void update(int i) {
        System.out.println("Observer1:myValue in subject is now :" + i);
    }
}

class Observer2 implements IObserver{

    @Override
    public void update(int i) {
        System.out.println("Observer2:myValue in subject is now :" + i);
    }
}
interface ISubject {
    void register(IObserver observer);
    void unregister(IObserver observer);
    void notifyObservers(int i);
}

class Subject implements ISubject {
    private int myValue;
     List<IObserver> observersList = new ArrayList<IObserver>();

    public int getMyValue() {
        return myValue;
    }

    public void setMyValue(int myValue) {
        this.myValue = myValue;
        notifyObservers(myValue);
    }

    @Override
    public void register(IObserver observer) {
        observersList.add(observer);
    }

    @Override
    public void unregister(IObserver observer) {
        observersList.remove(observer);
    }

    @Override
    public void notifyObservers(int updateValue) {
        for (int i = 0; i < observersList.size(); i++) {
            observersList.get(i).update(updateValue);
        }
    }
}

class ObserverPatternEx {
    public static void main(String[] args) {

        System.out.println("***Observer Pattern Demo***\n");

        Subject sub = new Subject();
        Observer1 observer1 = new Observer1();
        Observer2 observer2 = new Observer2();

        sub.register(observer1);
        sub.register(observer2);

        sub.setMyValue(5);
        System.out.println();
        sub.setMyValue(25);
        System.out.println();

        //unregister observer1 only
        sub.unregister(observer1);
       //Now only observer2 will observer the change

        sub.setMyValue(100);

    }

}

